package com.x52im.rainbowchat.http.logic.pay.redenvelope;

import com.alibaba.fastjson.JSON;
import com.eva.epc.common.util.CommonUtils;
import com.x52im.rainbowchat.http.logic.LogicUtils;
import com.x52im.rainbowchat.http.logic.dto.RedEnvelopeDTO;

import java.util.List;
import java.util.Optional;
import java.util.Vector;

/**
 * 收红包
 */
public class MRedEnvelopeGet extends ARedEnvelope {
    @Override
    public String deal(RedEnvelopeDTO dto) throws Exception {
        List<RedEnvelopeDTO> envelopes = moneyDAO.queryRedEnvelopsRoot(dto, true);
        if (envelopes == null || envelopes.isEmpty()) {
            dto.setUNKNOWED("找不到红包");
            return JSON.toJSONString(dto);
        }
        RedEnvelopeDTO rootEnvelope = envelopes.get(0);
        if (!rootEnvelope.getParentId().equals("-1")) {
            dto.setUNKNOWED("请传入根红包ID");
            return JSON.toJSONString(dto);
        }
        if (!rootEnvelope.getUserUid().equals(dto.getUserUid())) {
            if (!CommonUtils.isStringEmpty(dto.getgId())) {
                boolean inSameGroup = LogicUtils.inSameGroup(dto.getUserUid(), rootEnvelope.getUserUid(), rootEnvelope.getgId());
                if (!inSameGroup) {
                    dto.setUNKNOWED("不同群不能领取红包");
                    return JSON.toJSONString(dto);
                }
            } else {
                boolean isFriend = LogicUtils.isFriend(dto.getUserUid(), rootEnvelope.getUserUid());
                if (!isFriend) {
                    dto.setUNKNOWED("非好友不能领取红包");
                    return JSON.toJSONString(dto);
                }
            }
        }

        List<RedEnvelopeDTO> subs = rootEnvelope.getSubRedEnvelopeDTOS();
        Optional<RedEnvelopeDTO> finded = subs.stream().filter(redEnvelope1 -> !CommonUtils.isStringEmpty(redEnvelope1.getUserUid())
                && redEnvelope1.getUserUid().equals(dto.getUserUid())).findFirst();
        RedEnvelopeDTO foundEnve = finded.orElse(null);
        if (foundEnve != null) {    // 领过的返回自己领的红包
            return JSON.toJSONString(foundEnve);
        } else {  // 没领过的,判断红包是不是领完了,是则返回全部领完
            if (rootEnvelope.getState().equals(RedEnvelopeDTO.STATE.STATE_FINISH_ALL.getState())) {
                dto.setFINISHAll();
                return JSON.toJSONString(dto);
            }
        }

        Optional<RedEnvelopeDTO> randomEnvOptional = subs.stream().filter(redEnvelope1 -> CommonUtils.isStringEmpty(redEnvelope1.getUserUid())).findAny();
        RedEnvelopeDTO randomEnve = randomEnvOptional.orElse(null);

        String _ranodmMoney = randomEnve.getTotalAmount();
        int ranodmMoney = Integer.parseInt(_ranodmMoney);
        String _total = db.querySingleItem("total", "missu_account", "user_uid=" + dto.getUserUid());
        int total = Integer.parseInt(_total);
        int totlaNew = total + ranodmMoney;

        randomEnve.setState(RedEnvelopeDTO.STATE.STATE_FINISH.getState());
        randomEnve.setMemo(RedEnvelopeDTO.STATE.STATE_FINISH.getStateMemo());

        Vector sqls = new Vector(2);
        Vector values = new Vector(2);
        // 更新红包状态
        sqls.add("UPDATE missu_red_envelope SET user_uid=?, state=?, memo=?, state_date=now() WHERE id=?");
        values.add(new Object[]{dto.getUserUid(), randomEnve.getState(), randomEnve.getMemo(), randomEnve.getId()});
        // 更新账户余额
        sqls.add("UPDATE missu_account SET total=?, state_date=now() WHERE user_uid=?");
        values.add(new Object[]{totlaNew, dto.getUserUid()});
        boolean update = db.update(sqls, values, true);

        if (update) {
            String count = db.querySingleItem("select count(1)  from missu_red_envelope a where a.parent_id =" + dto.getId() + " and a.state !=" + RedEnvelopeDTO.STATE.STATE_FINISH.getState());
            if (count.equals("0")) {
                sqls.clear();
                values.clear();
                sqls.add("UPDATE missu_red_envelope SET state=?, memo=?, state_date=now() WHERE id=?");
                values.add(new Object[]{RedEnvelopeDTO.STATE.STATE_FINISH_ALL.getState(), RedEnvelopeDTO.STATE.STATE_FINISH_ALL.getStateMemo(), dto.getId()});
                db.update(sqls, values, true);
            }
        }

        if (update) {
            return JSON.toJSONString(randomEnve.toMap());
        }

        randomEnve.setUNKNOWED("红包领取失败");
        return JSON.toJSONString(randomEnve.toMap());
    }

}
